package com.yunquan.ohana.ui.selectFrames

import android.app.Application
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.FramesEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import okhttp3.RequestBody.Companion.toRequestBody

class SelectFramesViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    val mFramesData = mutableListOf<FramesEntity>()
    val mCheckedFrames = mutableListOf<FramesEntity>()

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        getFrames()
    }

    private fun getFrames() {
        val map = mutableMapOf<String, Any>()
        val json = Gson().toJson(map)
        val body = json.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.getUserDeviceList(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<List<FramesEntity>>() {
                override fun onSuccess(result: List<FramesEntity>?) {
                    super.onSuccess(result)
                    mFramesData.clear()
                    result?.let {
                        val list = it.sortedByDescending { e -> e.online }
                        mFramesData.addAll(list)
                        ui.value = 0
                    }
                }
            })
    }
}